<template>
  <div class="varable-manage">
    <div class = 'pcocess-config__center'>
      <div class="process-config-wrap">
        <search ref="search" :inputTitle="'请输入变量名称或变量描述进行查询'" :currentPage="currentPage" :count="count" @exportMethod="exportAct" @inputChange="inputChangeAct" @turnPage="turnPageAct" :showTools="false"></search>
        <diyTable :tableHeader="tableHeader" :tableData="tableList" @exportAct="tableOpera"></diyTable>
      </div>
    </div>
    <left-slide :visible.sync='slideLeft' :title="operType === 'add' ? '添加变量' : '编辑变量'" @saveClick="handleVarCLick" @cancelClick="cancelClick" :showFooter="true">
      <div style="margin: 20px">
        <el-form :model="form" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm" label-position="top">
          <el-form-item label="变量名称：" prop="VarName">
            <el-input v-model="form.VarName" :disabled="operType === 'add' ? false : true"></el-input>
          </el-form-item>
          <el-form-item label="变量描述：">
            <el-input v-model="form.Memo"></el-input>
          </el-form-item>
          <div class="margin-t-15">
            <span>是否弹屏变量：</span>
            <el-radio-group v-model="form.PopVar">
              <el-radio :label="false">否</el-radio>
              <el-radio :label="true">是</el-radio>
            </el-radio-group>
          </div>
        </el-form>
      </div>
    </left-slide>
  </div>
</template>
<script>
  import Agent from '@/components/public-modules/cache/Agent'
  import { ivrSearch, handleFakePage } from '@/utils/m7Utils.js'
  import leftSlide from '@/components/ui-modules/newConfig/leftSlide.vue'
  import search from './base/search.vue'
  import diyTable from '@/components/ui-modules/diytable/index.vue'
  export default {
    name: 'variableManage',
    data () {
      return {
        tableHeader: [
          {prop: 'VarName', label: '变量名称'},
          {prop: 'Memo', label: '变量描述'},
          {prop: 'UpdateTime', label: '最后更新时间'},
          {prop: 'operaSet', label: '操作', width: 150, opera: [{actMethod: 'edit', actName: '修改'}, {actMethod: 'del', actName: '删除'}]}
        ],
        operType: '',
        rules: {
          VarName: { required: true, message: '请输入变量名称', trigger: 'blur' }
        },
        form: {
          VarName: '',
          Memo: '',
          PopVar: false
        },
        slideLeft: false,
        count: 0,
        currentPage: 1,
        dataList: [],
        currVarObj: '',
        oldPBX: '',
        handledList: [],
        tableList: []
      }
    },
    components: {
      search,
      diyTable,
      Agent,
      leftSlide
    },
    watch: {
      pbx () {
        let routerName = this.$route.meta.title
        if (routerName === 'variableManage') {
          console.log('varmanage')
          this.reshList()
        }
      }
    },
    computed: {
      pbx () {
        return this.$store.state.config.callCenter.currentPBX
      }
    },
    methods: {
      //  搜索列表
      inputChangeAct (val) {
        this.handledList = ivrSearch(this.totalList, val, ['Memo', 'VarName']) || []
        this.count = this.handledList.length || 0
        this.currentPage = 1
        this.tableList = handleFakePage(this.currentPage, this.handledList)
      },
      turnPageAct (val) {
        this.currentPage = val
        this.tableList = handleFakePage(this.currentPage, this.handledList)
      },
      //        添加刷新生效方法接收
      exportAct (val) {
        if (val === 'add') {
          this.addSipNum()
        } else if (val === 'refresh') {
          this.reshList()
        }
      },
      tableOpera (obj) {
        if (obj.actMethod === 'edit') {
          this.handleEdit(obj.data)
        } else if (obj.actMethod === 'del') {
          this.handleDel(obj.data)
        }
      },
      initData () {
        if (this.$store.state.session.ivrMap && this.$store.state.session.ivrMap[this.pbx]) {
          let ivrLine = this.$store.state.session.ivrMap[this.pbx].data.vars
          this.handleData(ivrLine)
        }
      },
      cancelClick () {
        this.slideLeft = false
      },
      handleVarCLick () {
        this.$refs['ruleForm'].validate((valid) => {
          if (valid) {
            let data = {
              VarName: this.form.VarName,
              Memo: this.form.Memo,
              PopVar: this.form.PopVar,
              Account: this.$store.state.session.account.account
            }
            if (this.operType === 'edit') {
              data._id = this.currVarObj._id
              data.PBX = this.pbx
            } else if (this.operType === 'add') {
              data.PBX = this.pbx
            }
            this.$store.dispatch('updateVar', data).then(resp => {
              if (resp && resp.success) {
                this.cancelClick()
                this.reshList()
              }
            })
          }
        })
      },
      addSipNum () {
        this.operType = 'add'
        this.slideLeft = true
        this.form = {
          VarName: '',
          Memo: '',
          PopVar: false
        }
        this.$refs['ruleForm'].resetFields()
      },
      fetchData () {
        this.$store.dispatch('queryRefreshVar', {Account: this.$store.state.session.account.account, PBX: this.pbx}).then(resp => {
          if (resp && resp.success) {
            this.$store.commit('SET_IVRMAP_DETAIL', {PBX: this.pbx, typeName: 'vars', data: resp.list || [], flag: 'data', node: this})
            console.log(this.$store.state.session.ivrMap && this.$store.state.session.ivrMap[this.pbx])
            this.handleData(resp.list)
          }
        })
      },
      handleData (list) {
        let _list = []
        this.count = list.length
        if (list.length !== 0) {
          for (let i = 0; i < list.length; i++) {
            let _obj = list[i]
            _obj.sipTypeName = this.getSipTypeName(_obj.ExtenType)
            _list.push(_obj)
          }
        }
        this.currentPage = 1
        this.totalList = _list
        this.handledList = _list
        this.tableList = handleFakePage(this.currentPage, this.handledList)
      },
      getSipTypeName (sipType) {
        let sipDic = this.$getCache('sipType')
        let str = ''
        if (sipDic && sipDic.length !== 0) {
          for (let i = 0; i < sipDic.length; i++) {
            if (sipDic[i].code_value === sipType) {
              str = sipDic[i].code_name
              break
            }
          }
        }
        return str
      },
      reshList () {
        this.fetchData()
      },
      handleEdit (row) {
        this.currVarObj = row
        this.slideLeft = true
        this.operType = 'edit'
        this.form = {
          VarName: row.VarName,
          Memo: row.Memo,
          PopVar: row.PopVar
        }
        this.$refs['ruleForm'].resetFields()
      },
      handleDel (row) {
        this.$confirm('确定要删除该变量吗？', this.$t('public.tip'), {
          confirmButtonText: this.$t('public.confirm'),
          cancelButtonText: this.$t('public.cancel'),
          cancelButtonClass: 'primary_btn',
          confirmButtonClass: 'primary_btn',
          type: 'warning'
        }).then(() => {
          let data = {
            _id: row._id,
            VarName: row.VarName,
            Memo: row.Memo,
            PopVar: row.PopVar,
            Account: row.Account,
            PBX: row.PBX
          }
          if (this.$store.state.session.ivrMap && this.$store.state.session.ivrMap[this.pbx]) {
            let thisVars = this.$store.state.session.ivrMap[this.pbx].data.vars
            let flag = row.VarName
            let isReturn = false
            for (let i = 0; i < thisVars.length; i++) {
              if (row.VarName === thisVars[i].VarName) {
                if (thisVars[i].Account === 'admin') {
                  isReturn = true
                  break
                }
              }
            }
            if (flag === 'FROM_DID' || flag === 'IS_RED_NUM' || flag === 'JOBNUM' || flag === 'KEY_OF_IVR' ||
              flag === 'KEY_SAT' || flag === 'VAL_OF_IVR_MENU' || flag === '__IVRKEY' || flag === '__STATISTIC') {
              isReturn = true
            }
            if (isReturn) {
              this.$message.error('系统内置变量，不能删除！')
              return false
            }
            this.$store.dispatch('deleteVar', data).then((res) => {
              if (res.success) {
                this.reshList()
                this.$message.success(this.$t('config.channel.deleteSuccess'))
              }
            })
          }
        })
      }
    },
    deactivated () {
      this.oldPBX = this.pbx
    },
    activated () {
      if (this.oldPBX !== this.pbx) {
        this.reshList()
      }
    },
    beforeMount () {
      this.$store.dispatch('getCache', {type: 'sipType'}).then(() => {
        this.fetchData()
      })
    }
  }
</script>

<style lang="stylus" scoped>
  @import "../../../../assets/common.styl"
  .varable-manage
    margin 20px
    overflow-y hidden
    display: flex;
    -ms-flex-direction: column;
    flex-direction: column;
    overflow-y: auto;
    font-size: 12px;
    .margin-t-15
      margin-top 15px
    .margin-l-10
      margin-left 10px
    .pag-wapper
      position: absolute;
      right: 15px;
      top: 14px;
    .main-color
      color $c-main
      cursor pointer
    .wapper
      display flex
      flex-direction column
    .tool
      position relative
      border 1px solid #e7e7eb
      border-bottom 0
      padding  12px 15px
      /*display flex*/
      justify-content space-between
    .primary_btn
      padding 0px 10px
      min-width 60px
    .del
      color $c-pink
</style>

